package br.perfiman.service.impl;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import br.perfiman.Constants.IRS;
import br.perfiman.model.Asset;
import br.perfiman.model.Trade;
import br.perfiman.model.DTOs.IRS_DTO;
import br.perfiman.service.IRSService;
import br.perfiman.service.TradeService;
import br.perfiman.utils.BussinessUtils;

/**
 *
 * @author Wagner Costa
 * @since 01/04/2008
 * @version 1.0
 *
 */
@Stateless
public class IRSServiceBean implements IRSService{
	
	@EJB
	private TradeService tradeService;

	public IRS_DTO getIRSByMonth(Integer month, Integer year) {
		Date[] dates = BussinessUtils.getMonthRange(month, year);
		IRS_DTO dto = getIRSByPeriod(dates[0], dates[1]);
		dto.setMonth(month);
		dto.setYear(year);
		return dto;
	}

	public IRS_DTO getIRSByDay(Date day) {
		return getIRSByPeriod(day, day);
	}

	public IRS_DTO getIRSByPeriod(Date initialDate, Date finalDate) {
		List<Trade> trades = tradeService.retrieveTradesByPeriod(initialDate, finalDate, TradeService.TRADES_TYPE_SELL);
		IRS_DTO irs = new IRS_DTO();
		for(Trade trade: trades){
			if(trade.getOperationType().equals(Trade.OPERATION_TYPE_MIX))
				continue;
			if(trade.getOperationType().equals(Trade.OPERATION_TYPE_COMMON)){
				if(trade.getAsset().getType().equals(Asset.TYPE_OPTIONS)){
					irs.setOptionsProfit(irs.getOptionsProfit() + trade.getProfit());
					irs.setOptionsIrsPayed(irs.getOptionsIrsPayed() + trade.getIrs());
				} else {
					irs.setCommomProfit(irs.getCommomProfit() + trade.getProfit());
					irs.setCommomIrsPayed(irs.getCommomIrsPayed() + trade.getIrs());
					irs.setMonthSell(irs.getMonthSell() + (trade.getQuantity() * trade.getPrice()));
				}
			} else {
				if(trade.getAsset().getType().equals(Asset.TYPE_OPTIONS)){
					irs.setOptionsDayTradeProfit(irs.getOptionsDayTradeProfit() + trade.getProfit());
					irs.setOptionsDayTradeIrsPayed(irs.getOptionsDayTradeIrsPayed() + trade.getIrs());
				} else {
					irs.setDayTradeProfit(irs.getDayTradeProfit() + trade.getProfit());
					irs.setDayTradeIrsPayed(irs.getDayTradeIrsPayed() + trade.getIrs());
				}
			}
		}
		if(irs.getMonthSell() >= IRS.FREE_SELL_QUOTE)
			irs.setCommomIrs(irs.getCommomProfit() * IRS.IRS_COMMON_MARKET);
		irs.setOptionsIrs(irs.getOptionsProfit() * IRS.IRS_COMMON_MARKET);
		irs.setDayTradeIrs(irs.getDayTradeProfit() * IRS.IRS_DAYTRADE);
		irs.setOptionsDayTradeIrs(irs.getOptionsDayTradeProfit() * IRS.IRS_DAYTRADE);
		return irs;
	}
}
